<?php
/**
 * 护理记录功能相关接口
 * @authors Hex (hex@zpdchina.com)
 * @date    2017-03-09 17:25:32
 * @version $Id$
 */

class HulijiluController extends Yaf_Controller_Abstract
{
    //获取巡查记录数据--用于Android端的service同步数据
    public function getHulijiluListAction()
    {
        //获取参数
        $request = $this->getRequest();
        $yiyuan_id = $request->getPost('yiyuan_id',0);
        $user_department = $request->getPost('user_department','');
        $zhuyuan_id = $request->getPost('zhuyuan_id','');
        $type = $request->getPost('type','');
        $start_riqi = $request->getPost('start_riqi','');
        $end_riqi = $request->getPost('end_riqi','');
        $jilu_state = $request->getPost('jilu_state');
//        if(empty($yiyuan_id))
//            Utility::apiJsonError(30001, '医院编号不能为空');
//        if(empty($user_department))
//            Utility::apiJsonError(30010, '科室不能为空');
        if(empty($zhuyuan_id))
            Utility::apiJsonError(30006, '患者住院编号不能为空');
        $hlws_mdl = new HuliWenshuDetailModel;
        $hulijilu = $hlws_mdl->getHuliList($zhuyuan_id,$yiyuan_id,$type,$start_riqi,$end_riqi,$jilu_state);
        $data['count'] = $hulijilu['count'];
        $data['state'] = !empty($hulijilu['result'])?'1':'0';
        $data['result'] = $hulijilu['result'];
        $data['error'] = 200;
        $data['msg'] = "";
        Utility::apiJsonResultExtends($data);
    }

    //获取一条护理记录
    public function getOneHulijiluDataAction()
    {
        //获取参数
        $request = $this->getRequest();
        $yiyuan_id = $request->getPost('yiyuan_id',0);
        $id = $request->getPost('hulijilu_id','');
        $biaodan_name = $request->getPost('biaodan_name','');
        $user_department = $request->getPost('user_department','');
//        if(empty($yiyuan_id))
//            Utility::apiJsonError(30001, '医院编号不能为空');
        if(empty($user_department))
            Utility::apiJsonError(30010, '科室不能为空');
        if(empty($id))
            Utility::apiJsonError(30022, '护理记录编号不能为空');

        $data = array();
        /*获取护理记录单项列表模板*/
        $data_temp_mod = new DataHulijiluTemplateModel;
        $huli_field = $data_temp_mod->ls($user_department,array(),$biaodan_name);
        //拼接字段
        $one_field = '';
        if(is_array($huli_field)&&!empty($huli_field)){
            foreach($huli_field as $key=>$value){
                if($value['xiangmu_leixing']=='multiedit' || $value['xiangmu_leixing'] == 'multieditdropedittext') {
                    $multi_field [] = $value['hulicol_name'];
                    $multi_field_arr[] = $value['hulicol_name'];
                }else{
                    $one_field .=  ",".$value['hulicol_name'];
                }
            }
        }
        // 去除最后一个逗号
        $one_field = rtrim($one_field, ',');
        $hulijilus_field = 'id AS hulijilu_id,zhuyuan_id,type,jilu_hushi_name,jilu_hushi_id'.$one_field;
       // $hulijilus_field = 'id AS hulijilu_id,zhuyuan_id,type,jilu_hushi_name'.$one_field;
        $hlws_mdl = new HuliWenshuDetailModel;
        $hulijilus = $hlws_mdl->getHuliInfo($id,$hulijilus_field);
        //获取多编辑的附属数据
        $datas = $hlws_mdl->getMultiInfo($id,$multi_field);
        $hulijilu = array();
        if(is_array($hulijilus)&&!empty($hulijilus)){
            foreach($hulijilus as $key => $one)
            {
                $hulijilu[$key] = $one;
            }
        }

        $hulijulu_multi = array();
        if(is_array($datas)&&!empty($datas)){
            foreach($datas as $key => $one){
                if(isset($one['valcol'])){
                    $hulijilu[$one['valcol']][] = array('basic_info'=>$one['basic_info'],'other_info'=>$one['other_info'],'last_info'=>$one['last_info'],'remark'=>$one['remark']);
                    $hulijulu_multi[] = $one['valcol'];
                }
            }
        }
        //补充空白选项
        if(is_array($multi_field_arr)&&!empty($multi_field_arr)){
            foreach($multi_field_arr as $val){
                if($hulijulu_multi && !in_array($val, $hulijulu_multi)){
                    $hulijilu[$val][] = array('basic_info'=>"",'other_info'=>"",'last_info'=>"",'remark'=>"");
                }
            }
        }

        //多编辑升级版数据返回
        foreach($huli_field as $key=>$value) {
            if ($value['xiangmu_leixing'] == 'multieditselect') {
                /*护理文书子项的明细 */
                $sub_data = $hlws_mdl->getMultiUpgradeInfo($id,$value['hulicol_name']);
                /*护理子项的名称列表项 */
                $sub_name_arr = $hlws_mdl->getSubName($value['id']);
                if (!empty($sub_data) && !empty($sub_name_arr)) {
                    foreach ($sub_data as $k => $ex) {
                        foreach ($sub_name_arr as $sub_name) {
                            //	 $new_val[$sub_name['name']] = $ex[$sub_name['val_name']]?$ex[$sub_name['val_name']].$sub_name['danwei']:$ex[$sub_name['val_name']];
                            $new_val['line'] = $k;
                            $new_val['key_type'] = $sub_name['name'];
                            $new_val['save_value'] = $ex[$sub_name['val_name']] ? $ex[$sub_name['val_name']] . $sub_name['danwei'] : $ex[$sub_name['val_name']];
                            $hulijilu[$value['hulicol_name']][] = $new_val;
                            unset($new_val);
                        }
                    }
                }
            }
        }
      //  $hulijilu = array_map("cube", $hulijilu);
//        //print_r($hulijilu);exit;
//        $hulijilu = array_map(function ($str) {
//            if(empty($str))
//                return "";
//        }, $hulijilu);


        /*end*/
        foreach ($hulijilu as $key=>$item)
        {
            if($item == "")
            {
                $hulijilu[$key] = "";
            }
        }
        $data['state'] = !empty($hulijilu)?'1':'0';
        $data['error'] = 200;
        $data['msg'] = "";
        $data['result'] = $hulijilu;
        Utility::apiJsonResultExtends($data);
    }
    public function cube($str)
    {
        if($str == ""||$str == "null")
        return "";
    }

    //保存护理记录
    public function uploadHuliDataAction()
    {
        //获取参数
        $request = $this->getRequest();
        $yiyuan_id = $request->getPost('yiyuan_id', 0);
        $data = $request->getPost('data', '');

       // $data = json_decode($data,true);
        $detail = array();
        $hlws_mdl = new HuliWenshuDetailModel;
        /*是否开启压缩 默认开启*/
        $compression_http_data = $request->getPost('compression_http_data','off');

        $data = json_decode(Utility::uncompress($data,$compression_http_data),true);
        if(!empty($data)) {
        	//删除数据
        	if($hlws_mdl->delhulijilu($data['0']['hulijilu_id'])){
        		//增加查询是否存在该医嘱
	            $n=0;
	            $tmp_arr = array();
	            foreach ($data['0'] as $key => $value) {
	                // 检测是否为json字符串
	                if(strpos($value,"}]") AND !empty($value)) {
	                    /* add by Hex @20161101 多编辑升级版数据 */
	                    $ret_data = json_decode($value,true);
	                    if(strstr($key,'@')){
	                        $key_arr=explode('@', $key);
	                        if(trim($key_arr[1]) == 'multieditselect'){//判断是哪种多编辑（新版还是旧版类型）
	                            unset($tmp_arr_new);
	                            $k = 0;
	                            foreach ($ret_data as $index=>$val) {
	                                $tmp_arr_new[$k]['wenshu_id'] = $data['0']['hulijilu_id'];
	                                $tmp_arr_new[$k]['content'] = trim($key_arr[0]);
	                                $tmp_arr_new[$k][$val['val_name']] = $val['save_value'];
	                                $tmp_arr_new[$k]['yiyuan_id'] = $yiyuan_id;
	                                if($val['line'] != $ret_data[$index + 1]['line']) //说明不是同一组数组数据
	                                	$k++;
	                            }
	                            
	                            Utility::multiInsert('zhuyuan_huli_wenshu_detail_content_extend',$tmp_arr_new);
	                        }else if( in_array(trim($key_arr[1]) ,['multiedit','multieditdropedittext'])){
	                        	
	                        	foreach ($ret_data as $cont) {
									$tmp_arr[$n]['wenshu_id'] = $data['0']['hulijilu_id'];
									$tmp_arr[$n]['content'] = trim($key_arr[0]);
									$tmp_arr[$n]['basic_info'] = $cont['jiancha_type'];
									$tmp_arr[$n]['other_info'] = $cont['jiancha_value'];
									$tmp_arr[$n]['last_info'] = $cont['jiancha_fangshi'];
									$tmp_arr[$n]['remark'] = $cont['beizhu_value'];
									$n++;
								}
								
							}
							
	                    }else{
	                        foreach ($ret_data as $cont) {
	                            $tmp_arr[$n]['wenshu_id'] = $data['0']['hulijilu_id'];
	                            $tmp_arr[$n]['content'] = $key;
	                            $tmp_arr[$n]['basic_info'] = $cont['jiancha_type'];
	                            $tmp_arr[$n]['other_info'] = $cont['jiancha_value'];
	                            $tmp_arr[$n]['last_info'] = $cont['jiancha_fangshi'];
	                            $tmp_arr[$n]['remark'] = $cont['beizhu_value'];
	                            $tmp_arr[$n]['yiyuan_id'] = $yiyuan_id;
	                            $n++;
	                        }
	                    }
	                    /* end */
	                } else
	                    $detail[$key] = $value;
	            }//exit;
	            $detail['id'] = $detail['hulijilu_id'];
	            $detail['type'] = $detail['biaodan_name'];
	            $res = $hlws_mdl->addData($detail);
	            if($res) {
	                // 插入zhuyuan_huli_wenshu_detail_content子表
	                Utility::multiInsert('zhuyuan_huli_wenshu_detail_content',$tmp_arr);
	            }
	
	            if(($detail['type'] == '普通护理记录单1' || $detail['type'] == '普通护理记录单2') && Yaconf::get("config$yiyuan_id.add_more_type") =='on' ){
	                //更改记录状态
	                $infos = $hlws_mdl->getHuliInfos($detail['zhuyuan_id'],$detail['type'],$detail['jilu_time']);
	                if(count($infos) > 1){
	                    $table = 'zhuyuan_huli_wenshu_detail';
	                    $setArr = array('jilu_state'  => 0);
	                    $colArr = ['zhuyuan_id','type','DATE(jilu_time)','yiyuan_id'];
	                    $valArr = [$detail['zhuyuan_id'],$detail['type'],date('Y-m-d',strtotime($detail['jilu_time'])),$yiyuan_id];
	                    CommonModel::updateRows($table, $setArr, $colArr, $valArr);
	                }
	            }
	            $return['state'] = $res?'1':'0';
	            Utility::apiJsonResultExtends($return);
	        }else{
	        	Utility::apiJsonError(30020, '数据重复，请删除');
	        }
            
        }else{
            Utility::apiJsonError(30019, 'data不能为空');
        }
    }


    //获取护理评估单 add by zh
    public function getTizhiPingguListAction(){
        $request = $this->getRequest();
        $zhuyuan_id = $request->getPost('zhuyuan_id',0);
        $yiyuan_id = $request->getPost('yiyuan_id',"");
        if($yiyuan_id === "" )
        {
            Utility::apiJsonError(20028, '请输入医院ID');
        }
        elseif(!ctype_digit("$yiyuan_id"))
        {
            Utility::apiJsonError(20027, '医院ID必须是整型');
        }
        $riqi = $request->getPost('riqi',"");
        if(!$zhuyuan_id){
            Utility::apiJsonError(20050, '住院编号不能为空');
        }
        $info = DB::select('id,jilu_hushi_name,jilu_time')
            ->from("zhuyuan_tizhi_pinggudan_detail")
            ->where("zhuyuan_id","=",$zhuyuan_id)
            ->and_where("yiyuan_id","=",$yiyuan_id);
        if($riqi){
            $info->and_where("jilu_time",">",$riqi);
        }
        $res = $info->execute()
            ->as_array();
        //$info = M("zhuyuan_tizhi_pinggudan_detail")->where($where)->field('id,jilu_hushi_name,jilu_time')->order("id DESC")->select();
        if($info){
            $data['state'] = '1';
            $data['result'] = $res;

        }else{
            $data['state'] = '1';
        }
        $data['error'] = 200;
        $data['msg'] = "";
        Utility::apiJsonResultExtends($data);

    }

}